package com.bodacn.storagescan;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantLock;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RecordQuantityActivity extends AppCompatActivity {

    @BindView(R.id.tv_userName)
    TextView tvUserName;
    @BindView(R.id.btn_return)
    ImageButton btnReturn;
    @BindView(R.id.txt_titleInv)
    TextView txtTitleInv;
    @BindView(R.id.liner_title)
    FrameLayout linerTitle;
    @BindView(R.id.tv_barcodeCaption)
    TextView tvBarcodeCaption;
    @BindView(R.id.edit_Barcode)
    EditText editBarcode;
    @BindView(R.id.btn_Scan)
    Button btnScan;
    @BindView(R.id.lv_employee)
    ListView lvEmployee;
    @BindView(R.id.iv3)
    TextView iv3;
    @BindView(R.id.tv_process)
    TextView tvProcess;
    @BindView(R.id.iv4)
    TextView iv4;
    @BindView(R.id.tv_quantity)
    TextView tvQuantity;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.tv_color)
    TextView tvColor;
    @BindView(R.id.tv_goods_no)
    TextView tvGoodsNo;
    @BindView(R.id.tv_size)
    TextView tvSize;
    @BindView(R.id.tv_DB)
    TextView tvDB;
    @BindView(R.id.tv_piece)
    TextView tvPiece;
    @BindView(R.id.tv_result_info)
    TextView tvResultInfo;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    String curLoginUserNo, curLoginUser, curLoginTime;//操作员所属部门等信息;
    String FormType = "", Caption = "", PrBarcode = "", PrHouseDeID = "", PrPartName = "", KeyGuid = "";
    String serviceUrl = "http://192.168.10.12/tvservice";
    String serviceUrlExt = "/BDService.asmx?wsdl";
    //拦截扫描枪输入部分
    String BarcodeStr = "";
    ScannerManager scannerManager;
    boolean ScanSign = false;
    JSONArray detailJSON;
    private final static int MSG_AllowScan = 9000;
    private final static int MSG_ScanBarcodeOver = 9001;
    ReentrantLock reentrantLock = new ReentrantLock();
    private String TAG = getClass().getSimpleName();

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (scannerManager.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    List<EmployeeBean> employeeBeans=new ArrayList<>();
    CommonAdapter<EmployeeBean>adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_quantity);
        ButterKnife.bind(this);

        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo = paramBundle.getString("LoginUserNo");
        curLoginUser = paramBundle.getString("LoginUser");
        curLoginTime = paramBundle.getString("LoginTime");
        serviceUrl = paramBundle.getString("serviceUrl");
        serviceUrlExt = paramBundle.getString("serviceUrlExt");
        FormType = paramBundle.getString("FormType");
        Caption = paramBundle.getString("Caption");
        //界面变量
        ((TextView) findViewById(R.id.tv_userName)).setText("用户:" + curLoginUser);
        txtTitleInv.setText("工序报工");
        KeyGuid = UUID.randomUUID().toString();

        //ScanBarcode("3");
        //ScanBarcode("3");


        adapter=new CommonAdapter<EmployeeBean>(this,employeeBeans,R.layout.employee_item) {
            @Override
            public void setConverView(CommonViewHolder myViewHolder, EmployeeBean employeeBean) {
                ((TextView)(myViewHolder.getView(R.id.tv_employee))).setText(employeeBean.getEmpName());
            }
        };
        lvEmployee.setAdapter(adapter);

        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
            @Override
            public void onResult(String code, String deviceName) {
                Log.d(TAG, "code= " + code);
                playRingtone();
                editBarcode.setText(code);
                ScanBarcode(editBarcode.getText().toString());
            }
        }, this);
        editBarcode.setInputType(InputType.TYPE_NULL);
        editBarcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editBarcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(editBarcode, InputMethodManager.SHOW_FORCED);
            }
        });
        editBarcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null) {
                    //Log.e("Debug","-----------------------------Debug-----------------------------");
                    //System.out.println(event);
                    if ((event.getAction() == KeyEvent.ACTION_UP) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        //System.out.println(editBarcode.getText().toString());
                        ScanBarcode(editBarcode.getText().toString());
                        return true;
                    }
                }
                return false;
            }
        });
        editBarcode.requestFocus();
        editBarcode.requestFocusFromTouch();
    }

    //插放音乐;
    private void playRingtone() {
        Uri notification = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

    }

    @OnClick({R.id.tv_clear, R.id.btn_return, R.id.btn_Scan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_clear:
                KeyGuid = UUID.randomUUID().toString();
                tvResultInfo.setText("");
                tvGoodsNo.setText("");
                tvQuantity.setText("");
                tvPiece.setText("");
                tvSize.setText("");
                tvColor.setText("");
                tvDB.setText("");
                tvOrder.setText("");
                tvProcess.setText("");
                tvStatus.setText("");
                employeeBeans.clear();
                adapter.notifyDataSetChanged();
                break;
            case R.id.btn_return:
                finish();
                break;
            case R.id.btn_Scan:
                ScanBarcode(editBarcode.getText().toString());
                break;
        }
    }

    //登陆校验;
    private void ScanBarcode(String paramBarcode) {
        hideIM(editBarcode);
        if (ScanSign == false) {
            ScanSign = true;
            //组织WebService地址;
            editBarcode.setText("");
            editBarcode.setHint(paramBarcode);
            String SqlComm = "Exec EmpWorkScan @Barcode='" + paramBarcode + "',@KeyGuid='" + KeyGuid + "',@OperType='ScanBarcode',@UserNo='" + curLoginUserNo + "'";
            PrBarcode = paramBarcode;
            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm);
        } else Toast.makeText(this, "请稍等或退出重进!", Toast.LENGTH_LONG).show();
    }


    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            hideIM(editBarcode);
            editBarcode.setEnabled(true);
            editBarcode.selectAll();
            editBarcode.requestFocus();
            ScanSign = false;
            switch (msgId) {
                case MSG_ScanBarcodeOver:
                    if (detailJSON != null) {
                        //填充屏幕
                        fillScreen(detailJSON);
                    }
                    break;
                case MSG_AllowScan:
                    ScanSign = false;
                    break;
                default:
                    break;
            }
        }
    };

    private void fillScreen(JSONArray jsonArray) {
        Log.e(TAG,"length;"+jsonArray.length());
        if (jsonArray != null) {
            try {
                if (jsonArray.length() > 0) {
                    //员工
                    if (jsonArray.getJSONObject(0).getString("DataType").equals("EmpList")) {
                        employeeBeans.clear();
                        employeeBeans.addAll( new Gson().fromJson(String.valueOf(jsonArray), new TypeToken<List<EmployeeBean>>() {
                        }.getType()));
                        adapter.notifyDataSetChanged();
                        //工序
                    } else if (jsonArray.getJSONObject(0).getString("DataType").equals("ProcList")) {
                        if (jsonArray.getJSONObject(0).has("ProcName")) {
                            tvProcess.setText(jsonArray.getJSONObject(0).getString("ProcName"));
                        }
                        if (jsonArray.getJSONObject(0).has("ProductNum")) {
                            tvQuantity.setText(jsonArray.getJSONObject(0).getString("ProductNum"));
                        }
                        //扫描
                    } else if (jsonArray.getJSONObject(0).getString("DataType").equals("Barcode")) {
                        Log.e(TAG,"DataType;DataType");
                        if (jsonArray.getJSONObject(0).has("OrderNo")) {
                            tvOrder.setText(jsonArray.getJSONObject(0).getString("OrderNo"));
                        }
                        if (jsonArray.getJSONObject(0).has("ClearEmpList")) {
                            if (jsonArray.getJSONObject(0).getString("ClearEmpList").equals("Y")){
                                employeeBeans.clear();
                                adapter.notifyDataSetChanged();
                            };
                        }
                        if (jsonArray.getJSONObject(0).has("ProcName")) {
                            tvProcess.setText(jsonArray.getJSONObject(0).getString("ProcName"));
                        }
                        if (jsonArray.getJSONObject(0).has("StyleNo")) {
                            tvGoodsNo.setText(jsonArray.getJSONObject(0).getString("StyleNo"));
                        }
                        if (jsonArray.getJSONObject(0).has("DBH")) {
                            tvDB.setText(jsonArray.getJSONObject(0).getString("DBH"));
                        }
                        if (jsonArray.getJSONObject(0).has("Color")) {
                            tvColor.setText(jsonArray.getJSONObject(0).getString("Color"));
                        }
                        if (jsonArray.getJSONObject(0).has("Size")) {
                            tvSize.setText(jsonArray.getJSONObject(0).getString("Size"));
                        }
                        if (jsonArray.getJSONObject(0).has("Number")) {
                            tvPiece.setText(jsonArray.getJSONObject(0).getString("Number"));
                        }
                        if (jsonArray.getJSONObject(0).has("ProductNum")) {
                            tvQuantity.setText(jsonArray.getJSONObject(0).getString("ProductNum"));
                        }
                        if (jsonArray.getJSONObject(0).has("OrderNo")) {
                            tvOrder.setText(jsonArray.getJSONObject(0).getString("OrderNo"));
                        }
                        if (jsonArray.getJSONObject(0).has("ResultInfo")) {
                            tvResultInfo.setText(jsonArray.getJSONObject(0).getString("ResultInfo"));
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        ScanSign = true;
        Runnable run = new Runnable() {
            @Override
            public synchronized void run() {
                try {
                    reentrantLock.lock();
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    ScanSign = false;
                    //往界面转数据;
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
//                        if (jsonArray.optJSONObject(0).has("OperType")) {
//                            if (jsonArray.optJSONObject(0).getString("OperType").equals("ScanBarcode") == true) {
                                detailJSON = jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_ScanBarcodeOver;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
//                            }
//                        }
                    } else {
                        Message msg = new Message();
                        msg.what = MSG_AllowScan;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //刷新界面;
                    ScanSign = false;
                    Message msg = new Message();
                    msg.what = MSG_AllowScan;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                    reentrantLock.unlock();
                } finally {
                    reentrantLock.unlock();
                }

            }

        };
        new Thread(run).start();

    }


    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }
}
